package com.zsrt.easyui.user.service.impl;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.zsrt.easyui.user.dao.UserDao;
import com.zsrt.easyui.user.entity.UserEntity;
import com.zsrt.easyui.user.service.UserService;


@Service
public class UserServiceImpl implements UserService {
	
	@Autowired
	private UserDao dao;
	
	@Transactional()
	public void add(UserEntity entity, Map<String, Object> map){
		
		//try{
			//影响的记录的行数
			
			dao.add(entity);
			
			String userName = entity.getUserName();
			
			//ExecutorException
			dao.counterByName(userName);
			
			//if(counter >1){
				//throw new  UserException("用户名不能重复...");
			//}
			//int aa = 2/0;
			//System.out.println(aa);
			map.put("code", "success");
			map.put("msg", "增加成功");
//		}catch(ArithmeticException e){
//			map.put("code", "failure");
//			map.put("msg", "增加失败");
//			e.printStackTrace();
//			throw new ArithmeticException("数学异常...");
//		}
	}
	
	@Transactional(readOnly=true)
	public void findWithPage(Map<String, Object> param,Map<String,Object> jieguo){
		
		
		int counter = dao.getTotalRows(param);
		
		//EasyUI 规定最少要有2个数据给到前台  
		//1:告诉前台一共有多少条数据total
		//2:我这一页有多少条记录 rows
		jieguo.put("total", counter);
		jieguo.put("rows", dao.findWithPage(param));
	}

	public UserEntity findById(int id) {
		return dao.selectByPrimaryKey(id);
	}
	
	@Transactional(propagation =Propagation.REQUIRED)
	public void update(UserEntity entity) {
		
		System.out.println("进入service...");
		//影响的记录的行数 可以回滚
		dao.updateByPrimaryKeySelective(entity);
		
		//1 ArithmeticException 可以回滚
		//System.out.println(2/0);
			
		//2 ExecutorException 可以回滚
		//throw new ExecutorException();
			
		//try {
			//3 Exception不可以回滚
			//throw new Exception("ss");
		//} catch (Exception e) {
			//e.printStackTrace();
		//}
		
	}
	
	@Transactional(propagation =Propagation.REQUIRED,rollbackFor=RuntimeException.class)
	public void deleteByIds(List<Integer> ids, Map<String, Object> map) throws RuntimeException {
		try{
			//影响的记录的行数
			dao.deleteByIds(ids);
			map.put("code", "success");
			map.put("msg", "删除成功");
		}catch(RuntimeException e){
			map.put("code", "failure");
			map.put("msg", "删除失败");
			e.printStackTrace();
			throw new RuntimeException();
		}
	}



}
